package com.scy.java.map;

import org.junit.Test;

import java.util.*;

public class TreeMapTest {
    @Test
    public void testHashTable(){
        Hashtable hashtable = new Hashtable<>();
        hashtable.put("number"+1,1);
        hashtable.put("number"+1,1000);//替换value的值
        hashtable.put("number"+2,2);
        hashtable.put("number"+3,3);
        hashtable.put("number"+4,4);
        hashtable.put("number"+5,5);
        //HashTable中key/value不能为null
//        hashtable.put(null,5);//NullPointerException
//        hashtable.put(1,null);//NullPointerException
        System.out.println(hashtable);
    }

    //定制排序
    /**
     *重构compareTo()方法的实现逻辑
     * 需求：先按照name从大到小的顺序排列，（降序）
     * 如若name相等则按照age从小到大的顺序排序（升序）
     */
    @Test
    public void testTreeMap(){
        TreeMap map = new TreeMap<>(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                if (o1 instanceof Person && o2 instanceof Person){
                    Person person1 = (Person) o1;
                    Person person2 = (Person) o2;
                    //先按照name从大到小的顺序排列，（降序）
                    //前面加负号表示降序
                    int compare = -person1.getName()
                            .compareTo(person2.getName());
                    if (compare != 0){
                        return compare;
                    }else {
                        //如若name相等则按照age从小到大的顺序排序（升序）
                        return Integer.compare(person1.getAge(), person2.getAge());
                    }

                }else {
                    throw new RuntimeException("类型不匹配");
                }
            }
        });
        //创建对象
        //T = 84 J = 74
        Person person1 = new Person("Tom",18);
        Person person2 = new Person("Jack",18);
        Person person3 = new Person("Tom",28);
        Person person4 = new Person("Role",20);
        Person person5 = new Person("Jack",99);
        //将对象添加到集合中
        map.put(person1,11);
        map.put(person2,12);
        map.put(person3,113);
        map.put(person4,21);
        map.put(person5,91);
        map.forEach((key,value)-> System.out.println(key+"\t"+value));

    }

    //TreeMap 自然排序
    @Test
    public void testPerson(){
        //T = 84 J = 74
        Person person1 = new Person("Tom",18);
        Person person2 = new Person("Jack",18);
        Person person3 = new Person("Luck",28);
        Person person4 = new Person("Role",20);
        Person person5 = new Person("Lisong",28);
        TreeMap treeMap = new TreeMap<>();
        treeMap.put(person1,11);
        treeMap.put(person2,12);
        treeMap.put(person3,113);
        treeMap.put(person4,21);
        treeMap.put(person5,91);
        Iterator iterator = treeMap.entrySet().iterator();
        while (iterator.hasNext()){
            Object obj = iterator.next();
            Map.Entry entry = (Map.Entry) obj;
            System.out.println(entry.getKey() +"\t"+ entry.getValue());

        }
    }
}
